/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/9 11:59
 */
import {getToken, removeToken, setToken} from "../../utils/auth";
import {GET_USER_INFO, SET_NAME, SET_TOKEN, SET_USER_TYPE, SET_USERNAME} from "../EventConstant";
import {getUserInfo, login, logout ,modifyPwd} from "../../api/login";
import UserType from "../../common/userType";

const user = {
    state: {
        token: getToken(),
        username: '',
        avatar: '',
        userType: UserType.unknown, // UserType, 0 unknown
    },
    mutations: {
        [SET_TOKEN]: (state, token) => {state.token = token},
        [SET_USERNAME]: (state, username) => {state.username = username},
        [SET_USER_TYPE]: (state, userType) => {state.userType = userType}
    },
    actions: {
        Login({commit}, userInfo) {
            const username = userInfo.username.trim()
            return new Promise((resolve, reject) => {
                login(username, userInfo.password, userInfo.userType).then(response => {
                    const token = response.data.token;
                    commit(SET_TOKEN, token);
                    commit(SET_USERNAME, username);
                    commit(SET_USER_TYPE, userInfo.userType);
                    setToken(token);
                    resolve();
                }).catch(error => {
                    reject(error);
                })
            })
        },
        Logout({commit}) {
            return new Promise((resolve, reject) => {
                logout().then(response => {
                    resolve(response);
                }).catch(error => {
                    reject(error);
                }).finally(() => {
                    commit(SET_TOKEN, "");
                    commit(SET_USERNAME, "");
                    commit(SET_USER_TYPE, UserType.unknown);
                    removeToken();
                })
            })
        },
        GetUserInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const data = res.data;
                    commit(SET_USERNAME, data.username);
                    commit(SET_USER_TYPE, data.userType);
                    resolve(res);
                }).catch(error => {
                    reject(error);
                })
            })
        }
    }
}

export default user;
